import type { PropsWithChildren, ReactElement } from 'react';
import { NativeScrollEvent, NativeSyntheticEvent, StyleSheet, useColorScheme } from 'react-native';
import Animated, {
    interpolate,
    useAnimatedRef,
    useAnimatedStyle,
    useScrollViewOffset,
} from 'react-native-reanimated';

import { ThemedView } from '@/components/ThemedView';
import React from 'react';

const HEADER_HEIGHT = 250;

type Props = PropsWithChildren<{
    headerImage: ReactElement;
    headerBackgroundColor: { dark: string; light: string };
    onScroll?:(event: NativeSyntheticEvent<NativeScrollEvent>) => void; // onScroll 类型定义
}>;

/* 
视觉滚动差的 scrollView
- 头部图像会根据滚动的位置缩放和上下移动，产生一种视差效果
- 头部背景颜色会根据设备的颜色模式自动调整，支持暗模式和亮模式。
- 组件通过 children prop 来显示可滚动的主要内容，并支持自定义头部图像。
*/
export default function ParallaxScrollView({
    children,
    headerImage,
    headerBackgroundColor,
    onScroll
}: Props) {
    const colorScheme = useColorScheme() ?? 'light';
    const scrollRef = useAnimatedRef<Animated.ScrollView>();
    const scrollOffset = useScrollViewOffset(scrollRef);

    const headerAnimatedStyle = useAnimatedStyle(() => {
        return {
            transform: [
                {
                    translateY: interpolate(
                        scrollOffset.value,
                        [-HEADER_HEIGHT, 0, HEADER_HEIGHT],
                        [-HEADER_HEIGHT / 2, 0, HEADER_HEIGHT * 0.75]
                    ),
                },
                {
                    scale: interpolate(scrollOffset.value, [-HEADER_HEIGHT, 0, HEADER_HEIGHT], [2, 1, 1]),
                },
            ],
        };
    });

    return (
        <ThemedView>
            <Animated.ScrollView ref={scrollRef} showsVerticalScrollIndicator={false} onScroll={onScroll} >
                <Animated.View
                    style={[
                        { backgroundColor: headerBackgroundColor[colorScheme] },
                        headerAnimatedStyle,
                    ]}>
                    {headerImage}
                </Animated.View>
                {children}
            </Animated.ScrollView>
        </ThemedView>
    );
}

